const express = require('express')
const router = express.Router()
const {
  getAllUsers,
  hasUserName,
  deleteUser,
  updateUser,
  addUser,
} = require('../services/UserService')
const { department } = require('../utils/userTypes')
const { trafficDepartmentPermission } = require('../utils/permissions')

// 获取所有用户信息
router.get('/all-users', async (req, res) => {
  const users = await getAllUsers()
  res.status(200).json({ msg: '用户列表', data: users, code: 1 })
})
// 新增部门用户信息
router.post('/add-user', async (req, res) => {
  const { userName, loginPwd } = req.body
  // 避免重复添加, 根据userName查询数据库
  const hasOrNot = await hasUserName(userName)
  if (hasOrNot) res.status(401).json({ msg: '用户名已存在', code: 0 })
  else {
    const user = await addUser({
      userName,
      loginPwd,
      userType: department,
      permission: trafficDepartmentPermission,
    })
    res.status(200).json({ msg: '注册成功', code: 1, userId: user.id })
  }
})
// 删除用户
router.delete('/delete-user/:id(\\d+)', async (req, res) => {
  const { id } = req.params
  const result = await deleteUser(id)
  if (result) res.status(200).json({ msg: '删除成功', code: 1 })
  else res.status(401).json({ msg: '删除失败', code: 0 })
})
//修改用户名和密码并下线用户
router.put('/modify-user', async (req, res) => {
  const { id, userName, loginPwd } = req.body
  // 避免重复添加, 根据userName查询数据库
  const hasOrNot = await hasUserName(userName, true) //true表示获取记录实例
  if (hasOrNot) {
    // 判断是否就是在修改自己的信息
    if (hasOrNot.id !== id) {
      res.status(401).json({ msg: '用户名已存在', code: 0 })
      return //退出函数
    }
  }
  const result = await updateUser(id, { userName, loginPwd, loginStatus: false })
  if (result) res.status(200).json({ msg: '修改成功', code: 1 })
  else res.status(401).json({ msg: '修改失败', code: 0 })
})
// 下线用户
router.put('/offline-user', async (req, res) => {
  const { id } = req.body
  const result = await updateUser(id, { loginStatus: false })
  if (result) res.status(200).json({ msg: '下线成功', code: 1 })
  else res.status(401).json({ msg: '下线失败', code: 0 })
})

module.exports = router
